package avicit.bdp.dms.tdm.service;

import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.dms.tdm.dao.BdpAssetDemandDAO;
import avicit.bdp.dms.tdm.dto.BdpAssetDemandDTO;
import avicit.bdp.dms.tdm.dto.BdpAssetDemandImportDTO;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.SysAutoCodeClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.JsonUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.commons.utils.StringUtils;
import avicit.platform6.core.common.baseservice.BaseService;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.excel.ExcelUtil;
import avicit.platform6.core.excel.Map2Bo;
import avicit.platform6.core.excel.imp.entity.ExcelImportResult;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryReqBean;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @金航数码科技有限责任公司
 * @作者：ZiyanYan
 * @邮箱：yanzy@avic.com
 * @创建时间： 2024-03-19 07:56
 * @类说明：数据资产需求表Service
 * @修改记录：
 */
@Service
public class BdpAssetDemandService extends BaseService<BdpAssetDemandDAO, BdpAssetDemandDTO> {

    private static final Logger logger = LoggerFactory.getLogger(BdpAssetDemandService.class);

    @Autowired
    private BdpAssetDemandDAO bdpAssetDemandDAO;

    @Autowired
    private ConvertColumnClient convertColumnClient;

    @Autowired
    private SysAutoCodeClient sysAutoCodeClient;

    /**
     * 按条件分页查询
     *
     * @param queryReqBean 查询条件
     * @return QueryRespBean<BdpAssetDemandDTO>
     */
    @Transactional(readOnly = true)
    public QueryRespBean<BdpAssetDemandDTO> findListByPage(QueryReqBean<BdpAssetDemandDTO> queryReqBean) {
        QueryRespBean<BdpAssetDemandDTO> queryRespBean = new QueryRespBean<>();
        List<BdpAssetDemandDTO> result = super.findByPage(queryReqBean);
        this.valueConvert(result);
        queryRespBean.setResultByList(result);
        return queryRespBean;
    }

    /**
     * 按条件查询
     *
     * @param queryReqBean 查询条件
     * @return List<BdpAssetDemandDTO>
     */
    @Transactional(readOnly = true)
    public List<BdpAssetDemandDTO> findList(QueryReqBean<BdpAssetDemandDTO> queryReqBean) {
        BdpAssetDemandDTO searchParams = super.getQueryEntity(queryReqBean);

        List<BdpAssetDemandDTO> result = super.findList(searchParams);
        this.valueConvert(result);
        return result;
    }

    /**
     * 通过主键查询单条记录
     *
     * @param id 主键id
     * @return BdpAssetDemandDTO
     */
    @Transactional(readOnly = true)
    @Override
    public BdpAssetDemandDTO get(String id) {
        BdpAssetDemandDTO bdpAssetDemandDTO = this.bdpAssetDemandDAO.get(id);
        //记录日志
        if (bdpAssetDemandDTO != null) {
            valueConvert(Arrays.asList(bdpAssetDemandDTO));
        }
        return bdpAssetDemandDTO;
    }

    /**
     * 新增对象
     *
     * @param bdpAssetDemandDTO 保存对象
     * @return String
     */
    @Transactional
    @Override
    public String insert(BdpAssetDemandDTO bdpAssetDemandDTO) {
        bdpAssetDemandDTO.setId(ComUtil.getId());
        bdpAssetDemandDTO.setDemandStatus(1);
        bdpAssetDemandDTO.setCreatedIp(ThreadContextHelper.getIp());
        PojoUtil.setSysProperties(bdpAssetDemandDTO, PlatformConstant.OpType.insert);
        if (1 == bdpAssetDemandDTO.getType()) {
            bdpAssetDemandDTO.setCreatedBy(ThreadContextHelper.getUserId());
        } else {
            //bdpAssetDemandDTO.setCreatedBy(sysAutoCodeClient.autoGenerationCodeValue("8a58a6c78e4120a2018e654834af2840", "ASSET_DEMAND_CODE", bdpAssetDemandDTO.getId(), false, null).get("autoCodeValue"));
            String userName = sysAutoCodeClient.autoGenerationCodeValue(null, "ASSET_DEMAND_CODE", "ASSET_DEMAND_CODE", false, null).get("autoCodeValue");
            bdpAssetDemandDTO.setCreatedBy(userName);
            bdpAssetDemandDTO.setSecretLevel("1");
        }
        Integer returnVal = bdpAssetDemandDAO.insert(bdpAssetDemandDTO);
        BdpLogUtil.log4Insert(bdpAssetDemandDTO);
        return returnVal.toString();
    }

    private String generateCreatedName() {
        Integer maxInt = bdpAssetDemandDAO.generateCreatedName();
        if (maxInt == null) {
            maxInt = 0;
        }
        return "游客" + (maxInt + 1);
    }

    /**
     * 批量新增对象
     *
     * @param dtoList 保存对象集合
     * @return int
     */
    @Transactional
    @Override
    public int insertBatch(List<BdpAssetDemandDTO> dtoList) {
        return super.insertBatch(dtoList);
    }

    /**
     * 修改对象全部字段
     *
     * @param bdpAssetDemandDTO 修改对象
     * @return int
     */
    @Transactional
    @Override
    public int updateAll(BdpAssetDemandDTO bdpAssetDemandDTO) {
        if (bdpAssetDemandDTO == null) {
            throw new BusinessException("修改对象不能为空！");
        }
        if (StringUtils.isEmpty(bdpAssetDemandDTO.getId())) {
            throw new BusinessException("修改对象的id不能为空！");
        }
        if (bdpAssetDemandDTO.getDemandStatus() == 2) {
            bdpAssetDemandDTO.setDemandStatus(3);
        }
        return super.updateAll(bdpAssetDemandDTO);
    }

    /**
     * 修改对象部分字段
     *
     * @param bdpAssetDemandDTO 修改对象
     * @return int
     */
    @Transactional
    @Override
    public int updateSensitive(BdpAssetDemandDTO bdpAssetDemandDTO) {
        if (bdpAssetDemandDTO == null) {
            throw new BusinessException("修改对象不能为空！");
        }
        if (StringUtils.isEmpty(bdpAssetDemandDTO.getId())) {
            throw new BusinessException("修改对象的id不能为空！");
        }
        return super.updateSensitive(bdpAssetDemandDTO);
    }

    /**
     * 批量更新对象
     *
     * @param dtoList 修改对象集合
     * @return int
     */
    @Transactional
    @Override
    public int updateBatch(List<BdpAssetDemandDTO> dtoList) {
        return super.updateBatch(dtoList);
    }

    /**
     * 按主键单条删除
     *
     * @param id 主键id
     * @return int
     */
    @Transactional
    @Override
    public int delete(String id) {
        int count = super.delete(id);
        return count;
    }

    /**
     * 批量删除数据
     *
     * @param ids id的数组
     * @return int
     */
    @Transactional
    @Override
    public int deleteByIds(String[] ids) {
        int count = super.deleteByIds(ids);
        return count;
    }

    /**
     * 日志专用，内部方法，不再记录日志
     *
     * @param id 主键id
     * @return BdpAssetDemandDTO
     */
    private BdpAssetDemandDTO findById(String id) {
        return super.get(id);
    }

    /**
     * 批量导入
     *
     * @return
     */
    @Transactional
    public ExcelImportResult importData(List<Map<String, String>> dataList, String formData) {
        List<BdpAssetDemandDTO> bdpAssetDemandSuccessList = new ArrayList<BdpAssetDemandDTO>();
        List<BdpAssetDemandImportDTO> bdpAssetDemandErrList = new ArrayList<BdpAssetDemandImportDTO>();
        Map<String, Object> formDataMap = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(formData)) {
            formDataMap = JsonUtil.parseJSON2Map(formData);
        }
        if (!CollectionUtils.isEmpty(dataList)) {
            Map<String, Map<String, String>> convertResultData = this.assembleData(dataList);
            for (Map<String, String> data : dataList) {
                if (StringUtils.isEmpty(data.get("errorInfo"))) {
                    //业务校验
                    BdpAssetDemandDTO dto = new BdpAssetDemandDTO();
                    Map2Bo.map2Pojo(data, dto);
                    bdpAssetDemandSuccessList.add(dto);
                } else {
                    BdpAssetDemandImportDTO dtoImp = new BdpAssetDemandImportDTO();
                    Map2Bo.map2Pojo(data, dtoImp);
                    bdpAssetDemandErrList.add(dtoImp);
                }
            }
            this.revValueConvert(bdpAssetDemandSuccessList, convertResultData);
            this.insertBatch(bdpAssetDemandSuccessList);
        }
        ExcelImportResult excelImport = ExcelUtil.createUploadHis(bdpAssetDemandSuccessList, bdpAssetDemandErrList, BdpAssetDemandImportDTO.class, formDataMap);
        SysLogUtil.log(new BdpAssetDemandDTO().getLogTitle(), new BdpAssetDemandDTO().getLogTitle() + "共导入" + excelImport.getTotalRecord() + "条,导入成功" + excelImport.getSuccessRecord() + "条,导入失败" + excelImport.getFailRecord() + "条。", PlatformConstant.OpType.fileImport, PlatformConstant.OpResult.success, ComUtil.getId(), "BDP_ASSET_DEMAND");
        return excelImport;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     *
     * @param bdpAssetDemandDTOList
     */
    private void valueConvert(List<BdpAssetDemandDTO> bdpAssetDemandDTOList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (BdpAssetDemandDTO bdpAssetDemand : bdpAssetDemandDTOList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, bdpAssetDemand.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, bdpAssetDemand.getReceivedBy());
            BusinessUtil.createConvertSet(convertFormData, "PLATFORM_FILE_SECRET_LEVEL", bdpAssetDemand.getSecretLevel());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);

            //循环设置Alias或Name的值
            for (BdpAssetDemandDTO bdpAssetDemand : bdpAssetDemandDTOList) {
                bdpAssetDemand.setCreatedName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, bdpAssetDemand.getCreatedBy()));
                bdpAssetDemand.setReceivedName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, bdpAssetDemand.getReceivedBy()));
                if (StringUtils.isEmpty(bdpAssetDemand.getCreatedName())) {
                    bdpAssetDemand.setCreatedName(bdpAssetDemand.getCreatedBy());
                }
                bdpAssetDemand.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, "PLATFORM_FILE_SECRET_LEVEL", bdpAssetDemand.getSecretLevel()));
            }
        }
    }

    /**
     * 通过平台API将字段名称转换为值，包括通用选择组件、通用代码
     * 基础数据中用户默认使用用户编号转换，部门、岗位、角色默认使用编码进行转换，群组使用名称进行转换
     *
     * @param bdpAssetDemandDTOList
     */
    private void revValueConvert(List<BdpAssetDemandDTO> bdpAssetDemandDTOList, Map<String, Map<String, String>> convertResultData) {
        //循环设置Alias或Name的值
        for (BdpAssetDemandDTO bdpAssetDemand : bdpAssetDemandDTOList) {
            bdpAssetDemand.setSecretLevel(BusinessUtil.convertFormat(convertResultData, "PLATFORM_FILE_SECRET_LEVEL", bdpAssetDemand.getSecretLevelName()));
        }
    }

    /**
     * 通过平台API将字段名称转换为值，包括通用选择组件、通用代码提前组装数据
     *
     * @param dataList
     */
    private Map<String, Map<String, String>> assembleData(List<Map<String, String>> dataList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (Map<String, String> data : dataList) {
            BusinessUtil.createConvertSet(convertFormData, "PLATFORM_FILE_SECRET_LEVEL", data.get("secretLevelName"));
        }
        return convertColumnClient.convertCodeToId(convertFormData);
    }
}

